package com.fjwt.gz.service.activity.platform.acte003;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.bo.RealnameBo;
import com.fjwt.gz.core.third.interfaces.RealNameAuthInterface;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.bo.ActivityAwardBO;
import com.fjwt.gz.db.bo.ActivityUserTimesBO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.entity.FansAuthEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 预约有礼
 */
@Slf4j
@Service
public class ACTE003Service extends BaseActivityService<Object> {

    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private SendAwardService sendAwardService;
    @Autowired
    private FansAwardService fansAwardService;

    @Autowired
    private ActivitySettingService activitySettingService;
    @Autowired
    private AwardSettingService awardSettingService;
    @Autowired
    private FansAuthService fansAuthService;
    @Autowired
    private AgentInfoService agentInfoService;

    @Value("${province.code}")
    private String provinceCode;

    /**
     * 参与活动
     */
    @Override
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        super.takePartIn(fansActivityDTO);

        String extJson = fansActivityDTO.getExtJson();
        if (StringUtils.isBlank(extJson)) {
            throw new BizException("预约信息缺失");
        }

        Long activityChannelId = fansActivityDTO.getActivityChannelId();
        JSONObject jsonObject = JSONObject.parseObject(extJson);
        String name = jsonObject.getString("name");
        if (StringUtils.isEmpty(name)) {
            throw new BizException("预约姓名不能为空！");
        }
        String phone = jsonObject.getString("phone");
        if (StringUtils.isEmpty(phone)) {
            throw new BizException("预约手机号不能为空！");
        }
        log.info("参与活动参数：{}", jsonObject.toJSONString());
        String codeJsonStr = RedisUtil.getString(CS.getBookGiftSendMsg(CS.SYS_ROLE_TYPE.MCH, phone));
        if (StringUtils.isEmpty(codeJsonStr)) {
            throw new BizException("验证码已过期，请重新点击发送验证码！");
        }
        JSONObject codeJson = JSONObject.parseObject(codeJsonStr);
        String cacheCode = codeJson.getString("code");
        if (StringUtils.isEmpty(cacheCode) || !cacheCode.equalsIgnoreCase(jsonObject.getString("code"))) {
            throw new BizException("验证码错误！");
        }

        AgentInfoEntity agentInfoEntity = agentInfoService.getAgentInfo(fansActivityDTO.getLocationAgentNo());

        // 检测用户参与限制条件
        JSONObject limitJson = activitySettingService.checkActivitySetting(fansEntity, fansActivityDTO.getAppId(), redisOutTime, activityEntity);

        Long fansId = fansActivityDTO.getFansId();
        String appId = fansActivityDTO.getAppId();
        //检测活动奖品配置
        List<ActivityAwardAndSettingBo> activityAwardList = awardSettingService.getActivityAwardList(fansActivityDTO.getActivityId(), redisOutTime);

        List<ActivityAwardBO> activityAwardBOList = activityAwardService.getAwardList(activityAwardList);
        // 实名状态
        Integer isAuth = jsonObject.getInteger("isAuth");
        AtomicReference<ActivityAwardVO> activityAwardVO = new AtomicReference<>();

        // 查询用户实名信息
        FansAuthEntity fansAuthEntity = fansAuthService.getOne(FansAuthEntity.gw()
                .eq(FansAuthEntity::getAgentNo, fansActivityDTO.getLocationAgentNo())
                .eq(FansAuthEntity::getFansId, fansId));

        // 客户实名状态
        if (Constants.IS_AUTH.YES == (isAuth)) {
            // 客户实名
            if (ObjectUtils.isNotEmpty(fansAuthEntity) && ObjectUtils.isNotEmpty(fansAuthEntity.getCstmNo())) {
                sendAward(fansId, appId,  activityChannelId, activityAwardBOList, activityAwardVO, "B", agentInfoEntity);
            } else {
//                throw new BizException("您未办理长春邮政储蓄卡，您是新客用户");
                String authBankCard = jsonObject.getString("authBankCard");
                if (StringUtils.isEmpty(authBankCard)) {
                    throw new BizException("预约银行卡号不能为空！");
                }
                RealnameBo realnameBo = new RealnameBo();
                realnameBo.setName(name);
                realnameBo.setPhone(phone);
                realnameBo.setIdCard(jsonObject.getString("idCard"));
                realnameBo.setBankCard(authBankCard);
                realnameBo.setLocationAgentNo(fansActivityDTO.getLocationAgentNo());
                //主动调实名接口
                RealNameAuthInterface realNameAuthInterface = SpringBeansUtil.getBean(provinceCode + "RealNameAuthService", RealNameAuthInterface.class);
                JSONObject respJson = realNameAuthInterface.realNameAuth(realnameBo);
                if (respJson != null && "Y".equals(respJson.getString("isAuth"))) {
                    sendAward(fansId, appId, activityChannelId, activityAwardBOList, activityAwardVO, "B", agentInfoEntity);
                } else {
                    throw new BizException("实名认证失败，您是新用户");
                }
            }
        } else {
            // 客户非实名
            if (ObjectUtils.isNotEmpty(fansAuthEntity) && ObjectUtils.isNotEmpty(fansAuthEntity.getCstmNo())) {
                throw new BizException("您已完成实名认证，您是老客用户");
            } else {
                sendAward(fansId, appId, activityChannelId, activityAwardBOList, activityAwardVO, "A", agentInfoEntity);
            }
        }
        //更新Redis中参与的次数
        ActivityUserTimesBO activityUserTimesBO = limitJson.getObject("activityUserTimesBO", ActivityUserTimesBO.class);
        if (ObjectUtils.isNotEmpty(activityUserTimesBO)){
            activitySettingService.updateRedisParticipateNum(limitJson.getString("currentTimesKey"), activityUserTimesBO, redisOutTime);
        }
        Boolean userJoinScoreValue = limitJson.getObject("userJoinScoreValue", Boolean.class);
        if (ObjectUtils.isNotEmpty(userJoinScoreValue)){
            RedisUtil.set(limitJson.getString("userJoinScoreKey"), userJoinScoreValue, redisOutTime, TimeUnit.MILLISECONDS);
        }

        return activityAwardVO.get();
    }

    private void sendAward(Long fansId, String appId, Long activityChannelId, List<ActivityAwardBO> activityAwardBOList, AtomicReference<ActivityAwardVO> activityAwardVO, String remark, AgentInfoEntity agentInfoEntity) {
        activityAwardBOList.stream().filter(item -> remark.equals(item.getActivityAwardRemark())).forEach(
                item -> {
                    log.info("用户fansId：{},发放{}卡券", fansId, item.getActivityAwardRemark());
                    LambdaQueryWrapper<FansAwardEntity> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(FansAwardEntity::getFansId, fansId);
                    queryWrapper.eq(FansAwardEntity::getAwardId, item.getAwardId());
                    queryWrapper.eq(FansAwardEntity::getAwardType, item.getAwardType());
                    queryWrapper.eq(FansAwardEntity::getState, Constants.FANS_AWARD_STATE.ACTIVATE);
                    List<FansAwardEntity> fansAwards = fansAwardService.list(queryWrapper);
                    if (null == fansAwards || fansAwards.isEmpty()) {
                        long fansAwardId = sendAwardService.sendActivateAward(fansId, appId, item.getAwardId(), item.getAwardType(), activityEntity.getEndTime(), item.getActivityAwardRemark(), activityChannelId, null, null, agentInfoEntity);
                        item.setFansAwardId(fansAwardId);
                        activityAwardVO.set(activityAwardService.toUserData(item));
                    } else {
                        throw new BizException("您已存在预约信息");
                    }
                }
        );
    }
}